<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
import echarts from 'echarts'
import resize from '@/views/dashboard/mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    yearList: {
      type: Array,
      default: () => []
    },
    plantType: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    plantType: {
      handler(newVal) {
        if(newVal.length > 0) {
          this.setOptions()
        }
      }
    },
    yearList: {
      handler(newVal) {
        if(newVal.length > 0) {
          this.setOptions()
        }
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if ( !this.chart ) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el)
      this.setOptions()
    },
    setOptions() {
      const colorList = ['#FD4E4E', '#38D6FC', '#2FC66F', '#FE942C']
      const series = this.plantType.map( (item, index) => {
        return {
          name: item.name,
          type: 'line',
          smooth: true,
          emphasis: {
            focus: 'series'
          },
          itemStyle: {
            normal: {
              color: colorList[index % colorList.length],
              lineStyle: {
                color: colorList[index % colorList.length]
              }
            }
          },
          data: item.total
        }
      })
      const option = {
        tooltip: {
          trigger: 'axis',
          // axisPointer: {
          //   type: 'cross',
          //   label: {
          //     backgroundColor: '#6a7985'
          //   }
          // }
        },
        legend: {
          x: 'right',      //可设定图例在左、右、居中
          y: 'center',
          align: 'left',
          orient: 'vertical',
          // data: ['青贮玉米', '苜蓿草', '燕麦草', '籽粒玉米']
          data: this.plantType.map( item => {
            return item.name
          })
        },
        grid: {
          left: '3%',
          right: '15%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.yearList
          }
        ],
        yAxis: [
          {
            type: 'value',
            name:'价格(元/公斤)',
          }
        ],
        series
      };
      this.chart.setOption(option);
    }
  }
}
</script>
